import ika
import framethrottle
import controls
#import os # wtf not included with standard Python.

music = None
music_filename = ""
timer = None
font = None
render_list = None
update_list = None
input_list = None

DEBUG_SHOW_FPS = True

def FileExists(f):
    try:
        file = open(f)
    except IOError:
        return False
    return True

def DrawFPS():
    font.Print(5, 5, "FPS: " + str(timer.frame_rate))

def Startup():
    global timer
    global font
    global render_list, update_list, input_list
    
    timer = framethrottle.Timer()
    font = ika.Font("vinque.fnt")
    render_list = []
    update_list = []
    input_list = []

def Render():
    for callback in render_list:
        callback()
        
def Update():
    for callback in update_list:
        callback()
        
def Input(held, pressed):
    for callback in input_list:
        callback(held, pressed)

def PlayMusic(filename, loop=True):
    global music, music_filename
    if music and music_filename != filename:
        StopMusic()
    if FileExists(filename):
        music_filename = filename
        music = ika.Music(filename)
        music.loop = int(loop)
        music.Play()
    
def StopMusic():
    global music, music_filename
    if music:
        music_filename = ""
        music.Pause()
        music = None

def MainLoop():
    while 1:
        Render()
        if DEBUG_SHOW_FPS:
            DrawFPS()
        ika.Video.ShowPage()

        ika.Input.Update()
        held, pressed = controls.GetButtons()
        
        timer.Input(held, pressed)
        timer.Update()
        
        for i in range(timer.gap):
            Input(held, pressed)
            Update()
            ika.Input.Update()
            held, pressed = controls.GetButtons()
         


Startup()